<template>
  <m-container class="confirm-in">
    <in-work-top-cell :info="form" />
    <m-cell-group weight="label" :border="false">
      <m-cell label="派送方式" size="xs" />
      <m-cell title="派送方式" size="xs">
        <view class="center" slot="center" style="margin-left: -30rpx">
          <m-radio-group inline v-model="form.deliveryType" @change="handleChangeDeliveryType">
            <m-radio :label="+val" v-for="(key, val) in deliveryTypeMap" :key="val">{{ key }} </m-radio>
          </m-radio-group>
        </view>
      </m-cell>
    </m-cell-group>
    <template v-if="form.deliveryType === 1">
      <m-cell-group weight="label" :border="false">
        <m-cell label="目标站点" size="xs" />
        <m-cell size="xs">
          <view class="row" slot="center" style="margin-right: -8rpx">
            <radio-select v-model="form.type" />
          </view>
        </m-cell>
      </m-cell-group>
      <m-cell-group weight="label" :border="false">
        <m-cell label="人工指定库位" size="xs" />
        <m-cell title="计划入库位" size="xs">
          <view class="center" slot="center">
            <m-text :line="1"> {{ form.planDeliveryTargetCode }}</m-text>
            <m-button
              shape="round"
              background="#fff"
              size="md"
              plain
              height="76rpx"
              width="220rpx"
              @click="handleSelectCode"
            >
              选择库位
            </m-button>
          </view>
        </m-cell>
        <m-cell title="实际入库位" size="xs">
          <view class="center" slot="center">
            <m-text :line="1"> {{ form.deliveryTargetCode }}</m-text>
            <m-button
              shape="round"
              background="#fff"
              size="md"
              plain
              height="76rpx"
              width="220rpx"
              :disabled="form.planDeliveryTargetCode === ''"
              @click="handleScanStartCode"
            >
              扫描库位码
            </m-button>
          </view>
        </m-cell>
      </m-cell-group>
    </template>
    <template v-else-if="form.deliveryType === 2">
      <m-cell-group weight="label" :border="false">
        <m-cell label="当前站点" size="xs" />
        <m-cell title="地标码" size="xs">
          <view class="center" slot="center">
            <m-text :line="1"> {{ form.deliveryStartCode }}</m-text>
            <m-button
              shape="round"
              background="#fff"
              size="md"
              plain
              height="76rpx"
              width="220rpx"
              @click="handleScanStartCode"
            >
              扫描地标码
            </m-button>
          </view>
        </m-cell>
      </m-cell-group>
      <m-cell-group weight="label" size="sm" :border="false">
        <m-cell label="目标站点" size="xs" />
        <m-cell size="xs">
          <view class="row" slot="center" style="margin-right: -8rpx">
            <radio-select v-model="form.type" @change="handleChangeType" />
            <view v-if="form.type === 2" class="text">
              码头具体位置：{{ form.imsText }}/{{ form.deliveryTargetCodeTxt }}
            </view>

            <m-radio-group inline v-model="value" @change="handleChange" v-else>
              <m-radio
                :label="item.value"
                v-for="(item, index) in map[form.type]"
                :key="index"
                @click="handleRadioClick"
              >
                {{ item.name }}
              </m-radio>
            </m-radio-group>
          </view>
        </m-cell>
      </m-cell-group>
    </template>

    <in-work-layer v-model="show" @confirm="handleDeliveryTargetCode" :id="form.imsId" />
    <in-work-layer-station
      :pallet-code="form.palletCode"
      v-model="show1"
      @confirm="handleClickConfirmTargetCode"
      :id="form.imsId"
    />

    <m-fixed>
      <view class="footer">
        <m-button
          width="48.5%"
          plain
          size="xl"
          :disabled="!(form.deliveryTargetCode === '')"
          @click="handleClickSave"
          v-if="form.deliveryType === 1"
        >
          保存
        </m-button>
        <m-button
          :width="form.deliveryType === 1 ? '48.5%' : '100%'"
          size="xl"
          @click="handleClickConfirm"
          :disabled="getDisabled"
          >确认入库</m-button
        >
      </view>
    </m-fixed>
  </m-container>
</template>

<script>
import { isH5 } from '@/utils/platform'
const barcodeModel = uni.requireNativePlugin('iData-BarcodePlugin-BarcodeModule')
const globalEvent = uni.requireNativePlugin('globalEvent')
import { showModal } from '@/hooks'
import {
  getWorkOrder,
  imsStockInWork,
  imsDetectionStation,
  getIms,
  imsStockInWorkList,
  updateWorkOrderStatus,
  getCurrentPalletCode,
} from '@/api/modules/in-work'
import { deliveryTypeMap } from '@/utils/constant'
import { isAppPlus } from '@/utils/platform'
import { mapState } from 'vuex'
import { router } from '@/router'
import { map } from '@/utils/constant'
import RadioSelect from './components/radio-select'

export default {
  data() {
    return {
      value: 1,
      show: false,
      show1: false,
      form: {
        deliveryType: 2,
        deliveryStatus: 0,
        deliveryStartCode: isAppPlus
          ? ''
          : 'S' +
            Math.floor(Math.random() * 1000000)
              .toString()
              .padStart(6, '0'),
        deliveryTargetCode: '',
        planDeliveryTargetCode: '',
        type: 1,
        imsId: '',
      },
      map: {
        1: [],
        3: [
          { name: '系统分配', value: 1 },
          { name: '人工分配', value: 2 },
        ],
      },
      targetCode: '',
      deliveryTypeMap,
      options: null,
    }
  },
  components: {
    RadioSelect,
  },
  computed: {
    ...mapState({
      otherInfo: (state) => state.inWork.form,
    }),
    getIsSystemDistributor() {
      if (this.form.type === 2) {
        return [1].includes(this.value)
      }

      return [3].includes(this.form.type) && [2].includes(this.value)
    },
    getDisabled() {
      if (this.form.deliveryType === 1) {
        return this.form.deliveryTargetCode === ''
      }
      return false
    },
  },
  async onLoad(options) {
    this.options = options
    this.fetchData()
    barcodeModel.initScan()
    globalEvent.addEventListener('iDataBarcodeEvent', ({ barcode }) => {
      if (this.$Router.currentRoute.name !== 'ConfirmIn' || this.options === null) {
        return
      }

      if ((barcode.startsWith('S') || barcode.startsWith('WMS-S-')) && barcode.length === 12) {
        const { planDeliveryTargetCode, deliveryType } = this.form
        if (deliveryType === 2) {
          this.form.deliveryStartCode = barcode
        } else {
          if (planDeliveryTargetCode !== '' && planDeliveryTargetCode !== barcode) {
            showModal({
              title: '温馨提示',
              confirmText: '我知道了',
              content: `计划入库位码与实际入库位码不一致，计划入库位${planDeliveryTargetCode},实际入库位${barcode}`,
              showCancelButton: false,
              confirm: async () => {},
            })
            return
          }

          this.form.deliveryTargetCode = barcode
        }
      } else {
        uni.showToast({
          title: `请扫描正确的${this.form.deliveryType === 2 ? '地标码' : '库位码'}`,
          icon: 'none',
        })
      }
    })
  },
  onUnload() {
    this.form = {
      planDeliveryTargetCode: '',
      stationId: null,
      stationCode: null,
      stackNo: null,
      levelNo: null,
      locationNo: null,
      deliveryTargetCode: '',
    }
    this.options = null
    barcodeModel.closeScan()
  },
  methods: {
    handleSelectCode() {
      if (this.form.type === 3) {
        this.show1 = true
      } else if (this.form.type === 2) {
        this.show = true
      }
    },
    handleChangeDeliveryType() {
      this.form = {
        ...this.form,
        stationId: null,
        stationCode: null,
        stackNo: null,
        levelNo: null,
        locationNo: null,
        deliveryTargetCode: '',
      }

      this.map[3][1].name = `人工分配`
    },
    async fetchData() {
      const { data } = await getWorkOrder(this.options.inOrderId)
      const imsId = data.imsStockInOrderDetailList[0].imsId
      const {
        data: { defaultTargetStation },
      } = await getIms(imsId)

      const palletCode = await getCurrentPalletCode({ inOrderId: this.options.inOrderId })
      const res = await imsStockInWorkList({
        deliveryType: 1,
        palletCode,
      })

      if (res.rows.length) {
        this.form = {
          ...this.form,
          ...(res.rows[0] || {}),
        }
      }

      if (palletCode.length) {
        this.form.palletCode = palletCode
      }

      const params = {
        palletCode: this.otherInfo.palletCode,
        ...this.form,
        ...data,
        imsId,
        type: defaultTargetStation,
      }

      if (params.deliveryType === 1) {
        params.planDeliveryTargetCode = params.deliveryTargetCode
      }

      this.$set(this, 'form', params)
      this.handleChangeType(false)
      const { rows } = await imsDetectionStation({
        pageNum: 1,
        pageSize: 1000,
      })

      this.map[1] = rows.map((item) => ({ name: item.detectionStationCode, value: item.detectionStationId }))
      this.value = this.map[1][0].value
      this.targetCode = this.map[1][0].value
      this.form.deliveryTargetCode === ''
      this.handleChange()
    },
    handleDeliveryTargetCode(e) {
      const { deliveryType } = this.form
      this.form.deliveryTargetCode = deliveryType === 1 ? '' : e.code
      this.form.planDeliveryTargetCode = deliveryType === 1 ? e.barcode : ''
      this.form.deliveryTargetCodeTxt = e.codeTxt
      this.form.imsText = e.imsText
    },
    handleScanStartCode() {
      barcodeModel.scanStart((ret) => {
        console.log(7)
      })
    },
    handleClickConfirmTargetCode(e) {
      const { deliveryType } = this.form

      this.form = {
        ...this.form,
        ...e,
        deliveryTargetCode: deliveryType === 1 ? '' : e.stationCode,
        planDeliveryTargetCode: deliveryType === 1 ? e.barcode : '',
      }

      this.map[3][1].name = `人工分配 ${e.stackNo}-${e.levelNo}-${e.locationNo}`
    },
    handleClickConfirm() {
      this.loading = true
      try {
        if (this.form.deliveryType === 2) {
          if (this.form.deliveryStartCode === '') {
            uni.showToast({
              title: '请扫描地标码',
              icon: 'none',
            })
            this.loading = false
            return
          } else if (this.getIsSystemDistributor && this.form.deliveryTargetCode === '') {
            uni.showToast({
              title: '请选择目标位置',
              icon: 'none',
            })
            this.loading = false
            return
          }
        }

        showModal({
          title: '确认入库提示',
          content: '请问您确认要入库吗?',
          showCancelButton: true,
          confirm: async () => {
            await imsStockInWork({
              ...this.form,
              status: 0,
              type: 0,
              deliveryStatus: 0,
            })

            const { data } = await getWorkOrder(this.options.inOrderId)
            await updateWorkOrderStatus({
              ...data,
              status: 4,
            })
            this.loading = false
            this.$store.dispatch('inWork/setInfo', {})

            router.replaceAll({
              name: 'Index',
            })
          },
          cancel: () => {
            this.loading = false
          },
        })
      } catch (e) {
        this.loading = false
      }
    },
    handleChangeType(e) {
      if (this.form.type === 2) {
        this.show = !!e
        this.form.deliveryTargetCode = ''
      } else if (this.form.type === 3 && this.value === 2) {
        this.show1 = !!e
        this.form.deliveryTargetCode = ''
      } else if (this.form.type === 1) {
        this.value = this.targetCode
        this.form.deliveryTargetCode = this.value
      }
    },
    handleRadioClick(e) {
      if (this.form.type === 3 && e === 2) {
        this.show1 = true
      }
    },
    handleChange() {
      if (this.form.type === 1) {
        this.form.deliveryTargetCode = this.value
      } else if (this.form.type === 3) {
        this.form = {
          ...this.form,
          stationId: null,
          stationCode: null,
          stackNo: null,
          levelNo: null,
          locationNo: null,
          areaId: null,
          deliveryTargetCode: '',
        }
        this.map[3][1].name = `人工分配`
      }
      this.handleChangeType()
    },
    async handleClickSave() {
      const params = {
        ...this.form,
        status: 0,
        type: 0,
        deliveryStatus: 4,
      }

      if (this.form.deliveryType === 1) {
        params.deliveryTargetCode = this.form.planDeliveryTargetCode
      }

      const { data } = await imsStockInWork(params)
      this.form.inWorkId = data

      if (isH5) {
        this.form.deliveryTargetCode = this.form.planDeliveryTargetCode
      }

      uni.showToast({
        title: '操作成功',
        icon: 'none',
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.confirm-in {
  .center {
    padding-left: 80rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .text {
    text-align: center;
    font-size: 25rpx;
    color: #00a8f0;
    font-weight: bold;
  }
  .footer {
    display: flex;
    justify-content: space-between;
    gap: 20rpx;
  }

  ::v-deep {
    .cell-group__wrap {
      margin-bottom: 0;
    }
  }
}
</style>
